import axios from 'axios'
import qs from 'qs'
import { getToken, getLocalStorage } from './index'

class HttpRequest {
  constructor(baseUrl, prefix) {
    this.baseUrl = baseUrl + (prefix || '')
    this.queue = {}
  }

  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {}
    }
    if (process.env.NODE_ENV === 'production') {
      // config.headers['Auth-Token'] = getToken()
      // config.headers['Content-Type'] = 'application/json'
    }
    return config
  }

  destroy(url) {
    delete this.queue[url]
  }

  interceptors(instance, url, type) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      if (type == "form") {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      } else if (type == 'file') {
        config.headers['Content-Type'] = 'multipart/form-data'
      } else {
        config.headers['Content-Type'] = 'application/json'
      }
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data, status } = res
      const body = data
      return { body, status }
    }, error => {
      this.destroy(url)
      return Promise.reject(error)
    })
  }

  request(options) {
    const instance = axios.create()
    if (options.type == "form") {
      options.data = qs.stringify(options.data)
    }
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url, options.type)
    return instance(options)
  }
}
export default HttpRequest
